//电子邮件puhalskijsemen@gmail.com
//源码网站 开vpn全局模式打开 http://web3incubators.com/
//电报https://t.me/gamecode999
//网页客服 http://web3incubators.com/kefu.html

import ArrayUtils from "./ArrayUtils";
import GameConfig from "./GameConfig";
import { LoadingMgr } from "./LoadingManager";
import { LogMgr } from "./LogManager";
import { MiniGameSdk } from "./MiniGameSdk";
import { PlatformMgr } from "./PlatformManager";
import { PlayerDataMgr } from "./PlayerDataManager";
import { SingletonBase } from "./SingletonManager";
import { TipMgr } from "./TipsManager";

/**
 * 广告管理类
 * 建议类名：AdManager
 */
class ADManager extends SingletonBase {
    private _adInstance: any = null;
    private _successCallback: Function | null = null;
    private _failCallback: Function | null = null;
    private _currentRetryCount: number = 0;
    private _maximumRetryCount: number = 0;
    private _adTitle: string = '';

    /**
     * 打开分享功能
     * 设置分享标题和图片
     * @param shareTitle 分享标题
     * @param shareImage 分享图片
     */
    public setShareData(shareTitle: string, shareImage: string) {
        MiniGameSdk.API.showShareMenu();
    }

    /**
     * 
     */
    public shareGame(onSuccess?: (success: boolean) => void){
        MiniGameSdk.API.shareAppToFriendsNew("你敢来吃我吗","","https://mmocgame.qpic.cn/wechatgame/bSAKPPBBQFUN44PHyDL1mOY72Z1pA2eT0x3QtvGFxdL0ZPob1wej1Dy32ttBtt5y/0","",onSuccess)
    }

    /**
     * 显示激励视频广告
     * @param adTitle 广告标题
     * @param successCallback 成功回调
     * @param failCallback 失败回调
     * @param retryCount 最大重试次数，默认为3
     * 建议方法名：showRewardedVideoAd
     */
    public showRewardedVideoAd(adTitle: string, successCallback: Function, failCallback?: Function, retryCount: number = 3): void {
        this._adTitle = adTitle;
        if (PlatformMgr.isMiniGame() && !PlayerDataMgr.WHITE_NAME_NO_VIDEO) {
            if (!GameConfig.adConfig.ADUnitId || GameConfig.adConfig.ADUnitId.length === 0) {
                TipMgr.showToast("视频拉取失败");
                if (failCallback) {
                    failCallback();
                }
                return;
            }
            // 加载与显示激励视频广告
            MiniGameSdk.AdvertManager.instance.showVideo(GameConfig.adConfig.ADUnitId, (result: MiniGameSdk.EAdVideoResult, count: number) => {
                switch (result) {
                    case MiniGameSdk.EAdVideoResult.ACCEPT:
                        if (successCallback) {
                            successCallback();
                        }
                        break;
                    case MiniGameSdk.EAdVideoResult.REJECT:
                    case MiniGameSdk.EAdVideoResult.ERROR:
                        TipMgr.showToast("亲，广告没看完呢");
                        if (failCallback) {
                            failCallback();
                        }
                        break;
                    default:
                        break;
                }
            });
        } else {
            if (successCallback) {
                successCallback();
            }
        }
    }

    /**
     * 显示插屏广告
     * @param adUnitId 广告ID
     * 建议方法名：showInterstitialAd
     */
    public showInterstitial(adUnitId: string) {
        if (PlatformMgr.isMiniGame()) {
            MiniGameSdk.AdvertManager.instance.showInterstitial(adUnitId);
        }
    }

    /**
     * 加载banner
     * @param bannerId 广告ID
     * @param adLocation 广告显示位置
     * @param scale 缩放比例
     * 建议方法名：loadBannerAd
     */
    public loadBanner(bannerId: string, adLocation: MiniGameSdk.EAdBannerLocation = MiniGameSdk.EAdBannerLocation.TOP, scale: number = 1.0) {
        if (PlatformMgr.isMiniGame()) {
            MiniGameSdk.AdvertManager.instance.loadBanner(bannerId, adLocation, scale);
        }
    }

    /**
     * 显示横幅广告
     * 建议方法名：showBannerAd
     */
    public showBanner() {
        if (PlatformMgr.isMiniGame()) {
            MiniGameSdk.AdvertManager.instance.showBanner();
        }
    }

    /**
     * 隐藏横幅广告
     * 建议方法名：hideBannerAd
     */
    public hideBanner() {
        if (PlatformMgr.isMiniGame()) {
            MiniGameSdk.AdvertManager.instance.hideBanner();
        }
    }

    /**
     * 加载原生模板广告，不会显示。只有你在调用showCustom时才会显示。
     * 由于原生模板广告在微信服务后端可以定制宽度大小，个数，缩放比例等，所以位置调整要根据设置的宽度来定。抖音不支持本函数，会调用无效！
     * @param adUnitId 广告ID
     * @param topMargin 上间距
     * @param leftMargin 左间距
     * @param scale 缩放比例
     * 建议方法名：loadNativeTemplateAd
     */
    public loadCustom(adUnitId: string, topMargin: number = 0, leftMargin: number = 0, scale: number = 1) {
        if (PlatformMgr.isMiniGame()) {
            const wxInfo = window["wx"].getSystemInfoSync();
            const screenHeight: number = wxInfo.screenHeight;
            MiniGameSdk.AdvertManager.instance.loadCustom(adUnitId, { top: screenHeight - topMargin, left: leftMargin }, scale);
        }
    }

    /**
     * 显示原生模板广告
     * 建议方法名：showNativeTemplateAd
     */
    public showCustom() {
        if (PlatformMgr.isMiniGame()) {
            MiniGameSdk.AdvertManager.instance.showCustom();
        }
    }

    /**
     * 隐藏原生模板广告
     * 建议方法名：hideNativeTemplateAd
     */
    public hideCustom() {
        if (PlatformMgr.isMiniGame()) {
            MiniGameSdk.AdvertManager.instance.hideCustom();
        }
    }

    /**
     * 创建激励视频广告实例
     * @returns 激励视频广告实例
     * 建议方法名：createRewardedVideoAdInstance
     */
    private _createRewardedVideoAd(): any {
        if (!this._adInstance) {
            const adUnitId = this._getADUnitId();
            this._adInstance.onError(this._handleRewardedVideoAdError.bind(this));
            this._adInstance.onClose(this._handleRewardedVideoAdClose.bind(this));
            this._adInstance.onLoad(this._handleRewardedVideoAdLoaded.bind(this));
        }
        return this._adInstance;
    }

    /**
     * 播放激励视频广告
     * 建议方法名：playRewardedVideoAd
     */
    private _playRewardedVideo(): void {
        const adInstance = this._createRewardedVideoAd();
        adInstance.load().then(() => {
            adInstance.show();
        });
    }

    /**
     * 获取广告单元ID
     * @returns 广告单元ID
     * 建议方法名：getAdUnitId
     */
    private _getADUnitId(): string {
        const adUnitIds = GameConfig.adConfig.ADUnitId;
        return ArrayUtils.getRandomElement(adUnitIds);
    }

    /**
     * 激励视频广告加载错误处理
     * @param error 错误信息
     * 建议方法名：handleRewardedVideoAdError
     */
    private _handleRewardedVideoAdError(error: any): void {
        if (this._currentRetryCount < this._maximumRetryCount) {
            this._currentRetryCount++;
            this._playRewardedVideo();
        } else {
            TipMgr.showToast("视频加载失败，请稍后再试！");
            LoadingMgr.hide();
            LogMgr.debug("show reward video error: " + error);
        }
    }

    /**
     * 激励视频广告关闭处理
     * @param event 关闭事件
     * 建议方法名：handleRewardedVideoAdClose
     */
    private _handleRewardedVideoAdClose(event: any): void {
        LoadingMgr.hide();
        LogMgr.debug("reward video close " + JSON.stringify(event));
        if (event?.isEnded) {
            if (this._successCallback) {
                this._successCallback();
            }
            // CommonUtils.sendTrackingEvent(SendPointType.VideoMarking, this._adTitle);
        } else {
            if (this._failCallback) {
                this._failCallback();
            }
        }
    }

    /**
     * 激励视频广告加载成功处理
     * 建议方法名：handleRewardedVideoAdLoaded
     */
    private _handleRewardedVideoAdLoaded(): void {
        LogMgr.debug("reward video load success");
    }
}

export const ADMgr = ADManager.getInstance();